//	Title:		Duty Roster Admin Page
//	Author:		Bruce Frick
//	Purpose:	Set the data elements for today's Duty Roster.

var createFormDict = function(){
	//creates a dictionary to pass to addRowToTable() to build the display table
	var form_dict = {};
	form_dict['Provider'] = $("#providers option:selected").text();
	form_dict['ProviderID'] = $("#providers option:selected").val();
	form_dict['CaseManagers'] = $("#case_mgrs option:selected").text();
	form_dict['CaseManagersID'] = $("#case_mgrs option:selected").val();
	form_dict['CMALPN'] = $("#cma_lpn option:selected").text();
	form_dict['CMALPNID'] = $("#cma_lpn option:selected").val();
	form_dict['CMSSupport'] = $("#cms_support option:selected").text();
	form_dict['CMSSupportID'] = $("#cms_support option:selected").val();
	
	form_dict['ResourceCode'] = $("#resource_code").val();
	form_dict['Title'] = $("#title").val();
	form_dict['Shift'] = $("#the_shift").val();
	form_dict['Notes'] = $("#notes").val();

	return form_dict;
};


function fillForm(form_dict){
	clearElements();
}



function saveSuccessMsg() {	
	//javascript closer message and timeout
    var saveSuccess = function(){
		$("#save_msg").remove();
        clearTimeout(timeout_index);
        delete timeout_index;
    };
	
	//setting javascript closer to timeout after 6 seconds.  saveSuccess is a inline function (above)
    timeout_index = setTimeout(saveSuccess, 6000); 
	
	//javascript closer.  A message will apear after save, then disappear after 6 seconds.
	$(window).unload( function (){
        if( typeof(timeout_index) != 'undefined' ){
            //
        }
    });	
	
	//place save message next to save button.
	$("#publish_date").parent().append(" <span id='save_msg'>The Roster information has been saved.</span>");    
}


//pauls function.  Works Great!
function validDate(date){
	//var for required element error message.
	var date_message = " <span id='error_message'>Must be a valid date.</span>";
	
	//removes error messages from previous validation.
	$(".textbox_error").removeClass();
	$("span[id='error_message']").remove();
	$("#error").hide();
	
	//pauls date validator in action with jquery.
	var validator = new pdv();
	if (date.value.length > 0) {
		if (validator.IsSQLServerDate(date.value)){
			date.value = validator.DisplayDate(date.value, 'mm/dd/yyyy');			
		}else{		
			$("#error").show();
			$("#" + date.id + " ~ img").after(date_message);
			$("#" + date.id).addClass('textbox_error');	
		}
	}	
}


var validateElements = function(){
	//sets error count to zero, if greater then zero, some data is not valid
	var error_count = 0;
	
	//var for required element error message.
	var require_message = " <span id='error_message' style='display:block'>Field is required.</span>";
	
	//these fields are require on form.
	var required_fields = [];
	
	//removes error messages from previous validation.
	$(".textbox_error").removeClass();
	$("span[id='error_message']").remove();
	$("#error").hide();
	
	//if fields in the required_fields variable are empty this error is triggered.
	$.map(required_fields,function(field){
		if( !$("#" + field).val() )	{
			error_count++;
			$("#error").show();
			$("#" + field).after(require_message);
			$("#" + field).addClass('textbox_error');
		}
	});
		
	//if no errors in validation, well... the data is valid!
	if(error_count){return false;}else{return true;}
};



function tableToObjForInsert(){
	//create a dictionary object to pass to the submitForm function.
	var form_dict = {};	
	$.each($('#roster tbody tr'), function(i, n){	
		var tr = $(n).children();					
		form_dict['ProviderID'] = $(tr[1]).children().val();
		form_dict['ResourceCode'] = $(tr[2]).children().val();
		form_dict['Title'] = $(tr[3]).children().val();
		form_dict['Shift'] = $(tr[4]).children().val();
		form_dict['CaseManagerID'] = $(tr[5]).children().val();
		form_dict['CMAID'] = $(tr[7]).children().val();
		form_dict['CMSSupportID'] = $(tr[6]).children().val();
		form_dict['Notes'] = $(tr[8]).children().val();	
		form_dict['RosterDate'] = $('#roster_date').val();
		form_dict['Clinic'] = $('#clinic').val();
		submitForm(form_dict,"add_roster");			
	});
	
	//create a database entry for special instructions
	var form_dict = {};				
	form_dict['SpecialInstructions'] = $("#special_instructions").val();
	form_dict['Clinic'] = $("#clinic").val();
	form_dict['RosterDate'] = $("#roster_date").val();
	submitForm(form_dict,"add_special_instructions", "", saveSuccessMsg(), window.location.reload());
}



function bindElements(){
	//bind publish button to add table to database for selected date.
	$("#publish").bind("click", function(){
		tableToObjForInsert();
		return false;
	});
	
	//bind add_to_roster button to add a row of information to the display table.
	$("#insert_row").bind("click", function(){
		 addRowToTable( createFormDict() );
		 return false;
	});
	
	//bind delete button to remove all rows from roster table.
	$('#roster_rows input[type="button"]').bind("click", function(){
		removeRosterRow(this);
		return false;
	});
	
	//bind datepicer to reload page with selected date in url.
	$("#choose_roster_date").bind('change', function(){
		window.location.replace("admin.cfm?date=" + $("#choose_roster_date").val());
		return false;
	});
	
	//bind datepicer to reload page with selected date in url.
	$("#publish_date").bind('change', function(){
		$("#roster_date").val( $("#publish_date").val() );
		return false;
	});
	
	//bind table rows
	$("tr[id^='row_']").bind("dblclick", function(){		
		inlineEdit(this);
		return false;
	});
}


function inlineEdit(row){
	
	var inputValueList = $.map( $(row).children() , function(n){
		if( $(n).children().val() != 'Delete'){ return $(n).children().val() };		
	});

	$("#inline_edit").remove();
	var data_input = $("#data_input").clone();
	$(data_input).attr('id', 'inline_edit');
	$.each($(data_input).children(), function(i, n){
		var row_children = $(n).children();
		$(row_children[1]).attr('id', 'inline_edit_' + $(row_children[1]).attr('id') );
		//need a different treatment if input is a drop down
		if( i == 0 || i == 4 || i == 5 || i == 6 ){
			$( $(n).children()[1] ).val( inputValueList[i] ).attr('selected');
		}else{
			$( row_children[1] ).val();
		}
		
	});	
	$(row).after( data_input );
	$($(row).children()[0]).children().trigger('click');
	$(row).remove();	
	$("#inline_edit td:eq(0)").before("<td><input type='button' id='save_inline_edit' value='Save' /></td>");
	
	//bind save_inline_edit button to add a row of information to the display table.
	$("#save_inline_edit").bind("click", function(){
		var form_dict = {};
		
		form_dict['Provider'] = $("#inline_edit_providers option:selected").text();
		form_dict['ProviderID'] = $("#inline_edit_providers option:selected").val();
		form_dict['CaseManagers'] = $("#inline_edit_case_mgrs option:selected").text();
		form_dict['CaseManagersID'] = $("#inline_edit_case_mgrs option:selected").val();		
		form_dict['CMSSupport'] = $("#inline_edit_cms_support option:selected").text();
		form_dict['CMSSupportID'] = $("#inline_edit_cms_support option:selected").val();
		form_dict['CMALPN'] = $("#inline_edit_cma_lpn option:selected").text();
		form_dict['CMALPNID'] = $("#inline_edit_cma_lpn option:selected").val();
		form_dict['ResourceCode'] = $("#inline_edit_resource_code").val();
		form_dict['Title'] = $("#inline_edit_title").val();
		form_dict['Shift'] = $("#inline_edit_the_shift").val();
		form_dict['Notes'] = $("#inline_edit_notes").val();
		
		addRowToTable( form_dict );
		
		var delete_btn_td = $(row).children()[0];
		$(delete_btn_td).children().trigger('click');
		$("#inline_edit").remove();
		return false;
	});	
	
	//bind save_inline_edit button to add a row of information to the display table.
	$("#cancel_inline_edit").bind("click", function(){
		$(row).show();
		$("#inline_edit").remove();
		return false;
	});
}



function addRowToTable(obj){
	//build string to add to display table
	var row_count = $('#roster tbody tr').length + 1;
	var row = "<tr id='added_row_" + row_count + "'>";
	row = row + 
		"<td><input type='button' id='row_" + row_count + "' value='Delete' /> </td>" + 
		"<td><input type='hidden' value='" + obj['ProviderID'] + "' /> " + obj['Provider'] + " &nbsp;</td>" + 
		"<td><input type='hidden' value='" + obj['ResourceCode'] + "' /> " + obj['ResourceCode'] + " &nbsp;</td>" + 
		"<td><input type='hidden' value='" + obj['Title'] + "' /> " + obj['Title'] + " &nbsp;</td>" + 
		"<td><input type='hidden' value='" + obj['Shift'] + "' /> " + obj['Shift'] + " &nbsp;</td>" + 
		"<td><input type='hidden' value='" + obj['CaseManagersID'] + "' /> " + obj['CaseManagers'] + " &nbsp;</td>" + 		
		"<td><input type='hidden' value='" + obj['CMSSupportID'] + "' /> " + obj['CMSSupport'] + " &nbsp;</td>" +
		"<td><input type='hidden' value='" + obj['CMALPNID'] + "' /> " + obj['CMALPN'] + " &nbsp;</td>" + 
		"<td><input type='hidden' value='" + obj['Notes'] + "' /> " + obj['Notes'] + " &nbsp;</td>" ;
	row = row + "</tr>";
	
	//add variable row to display table
	$("#roster").append(row);
	
	//bind the newly created row to a click event
	$("#row_" + row_count).bind("click", function(){
		removeRosterRow(this);
	});
	
	//bind double click to inline edit of the row
	$("#added_row_" + row_count).bind("dblclick", function(){		
		inlineEdit(this);				  
	});
}



function removeAllRosterRows(){
	$("#roster_rows").remove();	
}


function removeRosterRow(obj){
	//remove parent row.  .parent().parent() finds the td then the tr.
	$(obj).parent().parent().remove();
	
	//delete row if in database already
	var form_dict = {AptID : $(obj).attr('id').split("_")[1]};
	submitForm(form_dict, "delete_roster_row");
}



function clearElements(){
	//reset all textboxes
	$(":input:not(input[type='button']):not(input[type='hidden'])").val("");
}



function submitForm(obj, api, id, successFunc, completeFunc, errorFunc){
	//ajax POST to add a to database.
	var api_url = "api.cfm?api=" + api + ( (id) ? "&id=" + id : "" );
	$.ajax({
		type:'POST', url:api_url, dataType: 'json', async: false, data: obj,
		success: function() {successFunc},
		complete: function(){completeFunc},
		error: function(err){errorFunc}
	});
}



$(function() {
	
	$("#special_instructions").tinymce({
		// General options
		theme : "advanced",
		theme_advanced_buttons1 :"bold,italic,underline,separator,strikethrough,justifyleft,"+ 
		"justifycenter,justifyright,justifyfull,bullist,numlist,undo,redo,forecolor,spellchecker,formatselect",
		theme_advanced_buttons2 : "",
		theme_advanced_buttons3 : "",		
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_resizing : true
	});
	
	//make meal_date textbox a datepicker
	$("#choose_roster_date, #publish_date").datepicker({ 
		dateFormat: 'mm/dd/yy', changeYear: true, changeMonth: true, /*yearRange: '1900:2010',*/ autoSize: true,
		prevText: 'Earlier', nextText: 'Later', showOn: 'button', 
		buttonImage: '/CFIDE/scripts/ajax/resources/cf/images/DateChooser.png', buttonImageOnly: true,
		onClose: function(dateText, inst) { $(this).focus()}
	});
	 
	bindElements();		
});